<template>

	<van-sticky>

		<van-search v-model="value" show-action placeholder="请输入您喜欢的热门产品" background="#B0352F" shape='round'
			@search="onSearch">

			<template #left>
				<van-icon name="arrow-left" @click='prev()' />
		 </template>

			<template #action>
				<div @click="onSearch">搜索</div>
			</template>
		</van-search>

	</van-sticky>


</template>

<script>
	import {mapActions} from 'vuex'
	
	export default {
		name: 'TopSearch',
		data() {
			return {
				value: '',
				searchHistory: [],
			}
		},
		watch: {
			"$route.query.value": {
				immediate: true, // 一开始的数据也要当做一种变化
				handler(val, old) {
					this.value = val
				}
			},
		},
		methods: {
			prev() {
				this.value = ''
				this.$router.back()
			},
			onSearch() {

				//判断字符串是否为空
				if (!!this.value) {

					//判读本地储存里是否有搜索记录，true将搜索记录存入数组
					if (!!localStorage.getItem('searchHistory')) {
						this.searchHistory = JSON.parse(localStorage.getItem('searchHistory'))
					}

					//不为空，将搜索关键词存入数组，然后存入本地浏览器缓存
					this.searchHistory.unshift(this.value);
					//去掉重复搜索关键词
					this.searchHistory = [...new Set(this.searchHistory)]
					//存入本地浏览器缓存
					window.localStorage.setItem('searchHistory', JSON.stringify(this.searchHistory));
					
					//判断搜索是否和上一次重复，重复不进行页面跳转
					if(this.$route.query.value == this.value) return
					this.searchList(this.value)
					//跳转到搜索结果
					this.$router.push({
						name: 'searchList',
						query: {
							value: this.value
						}
					})

				}

			},
			...mapActions('commodityList',['searchList']),
		},
		mounted() {
			//判读本地储存里是否有搜索记录，true将搜索记录存入数组
			if (!!localStorage.getItem('searchHistory')) {
				this.searchHistory = JSON.parse(localStorage.getItem('searchHistory'))
			}
		}

	}
</script>

<style scoped>
	div {
		color: #fff;
	}

	div:active {
		background-color: #B0352F;
	}

	.van-icon-arrow-left {
		font-size: 1.4375rem;
		margin-top: 0.125rem;
		margin-right: 0.4375rem;
	}

	.van-search {
		height: 2.875rem;
	}

	.van-search__content {
		height: 1.875rem;
	}
</style>
